package com.framework;

import java.io.File;


import org.cocos2dx.lib.Cocos2dxActivity;

import android.app.ActivityManager;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.pm.ApplicationInfo;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.net.wifi.WifiInfo;
import android.net.wifi.WifiManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.telephony.TelephonyManager;
import android.text.ClipboardManager;
import android.util.Log;


public class CCJNIHelper {

    private static int INSTALLED = 0; // 閻炴稏鍔庨妵姘啅閼碱剛鐥呴悗鐟邦槼椤ユ牠鏁嶇仦鑲╃懍閻犺櫣鍠撻獮鍥捶閵娿劎绠瑰☉鎾跺pk闁哄倸娲ｅ▎銏ゅ及椤栨瑧顏卞☉鎿冧簽婢ф寮甸敓锟�    private static int UNINSTALLED = 1; // 閻炴稏鍔庨妵姘跺嫉椤忓嫮鏆旈悷渚婃嫹
    private static int INSTALLED_UPDATE =2; // 閻炴稏鍔庨妵姘啅閼碱剛鐥呴悗鐟邦槼椤ユ牠鏁嶅畝锟芥晶妤呭嫉椤掍胶妲烽柣婊勬緲濠�亝娼诲▎搴ㄥ殝闁绘鐗婂﹢鎵啺娴ｉ绉甸柨娑樿嫰瑜板弶绂掗妷褍浠柛鎴犵帛鐎垫粓鏌﹂鑺ョ函闁哄偊鎷�
    private static Context context;





    // ===========================================================
    // Constants
    // ===========================================================

    // ===========================================================
    // Fields
    // ===========================================================
    private static Context sContext = null;
    private static String sPackageName = null;
    private static String sChannelID = null;
    private static CCJNIFuncListener sCCJNIHelperListener = null;
    private static String UserName = null;
    private static String Password = null;
    private static String m_strUserLoginInfo = null;
    private static int m_iEnterMode = 0;
    private static ClipboardManager m_Clipboard;
    // ===========================================================
    // Constructors
    // ===========================================================

    public static void init(final Cocos2dxActivity pContext,
                            final CCJNIFuncListener pCCJNIHelperListener) {
        final ApplicationInfo applicationInfo = pContext.getApplicationInfo();
        CCJNIHelper.sContext = pContext;
        CCJNIHelper.sCCJNIHelperListener = pCCJNIHelperListener;
        CCJNIHelper.sPackageName = applicationInfo.packageName;

        // 闁兼儳鍢茶ぐ鍥ㄧ▔閿熶粙鍤嬮柛鎿冧海閸掓盯寮堕幐搴㈢疀闁告棑绱曞▓鎴﹀矗閵夛妇鍔�
        m_Clipboard =(ClipboardManager)CCJNIHelper.sContext.getSystemService(Context.CLIPBOARD_SERVICE);

        Intent intent = pContext.getIntent();
        Bundle bundel = intent.getExtras();
        if (bundel != null)
        {
            String UserName = bundel.getString("UserName");
            String password = bundel.getString("password");
            String packageName = bundel.getString("packageName");
            m_iEnterMode = bundel.getInt("iEnterMode");

            m_strUserLoginInfo = UserName + ";" + password + ";" + packageName + ";" + m_iEnterMode;
        }

        try {
            ApplicationInfo ai = pContext.getPackageManager().getApplicationInfo(
                    pContext.getPackageName(), PackageManager.GET_META_DATA);
            sChannelID = ai.metaData.getString("TDGA_CHANNEL_ID");
        } catch (Exception e) {
            Log.e("error", "WTF!");
        }
    }

    // 闁兼儳鍢茶ぐ鍢媓annel ID
    public static String getChannelID() {
        return sChannelID;
    }

    // 閻犲洩顕цぐ鍥棘閸ワ附顐�SD闁告せ锟借尙鍠橀柛蹇撶墳缁辨繈宕ラ敃锟介崹顖涚瀹稿兎k濮掓稒顭堥鑽わ拷鐟邦槼椤ユ牠鎯勯鑲╃Э閻犲洩顕цぐ锟�
    // Cool.Cat
    public static String getReadWritePath() {

        // 濞村吋锚閸樻稑顕ラ敓绱诲☉鎾筹工閸熸捇鏁嶇仦绛嬫妇闁哄绮堢粭澶岋拷娑櫭﹢顏堟晬鐏炶棄鐏熼柛鎰懇缁垳鎷嬮妶鍡楊杹闁哄牆鎼悺銊╁磼閵娧冪畾濠⒀嶆嫹
    	Log.i("debug", "----------------------------------------");
		Log.i("debug", "getDataDirectory=" + Environment.getDataDirectory());
		Log.i("debug",
				"getDownloadCacheDirectory="
						+ Environment.getDownloadCacheDirectory());
		Log.i("debug",
				"getExternalStorageDirectory="
						+ Environment.getExternalStorageDirectory());
		Log.i("debug", "getRootDirectory=" + Environment.getRootDirectory());
		Log.i("debug", "----------------------------------------");
    	if (Environment.getExternalStorageState().equals(
                android.os.Environment.MEDIA_MOUNTED)) {
            File fp = Environment.getExternalStorageDirectory();
            fp = new File(fp.toString() + "/." + CCJNIHelper.sPackageName);
            fp.mkdirs();
            fp.setWritable(true);
            return fp.toString();
        }
        return "/data/data/" + CCJNIHelper.sPackageName;
    }

    // 闁告牕鎳庨幃锟�
    public static String getPackageName() {
        return CCJNIHelper.sPackageName;
    }

    // 妤犵偛寮剁敮锟�
    public static void killProcess() {
        android.os.Process.killProcess(android.os.Process.myPid());
    }

    // 闁哄嫷鍨伴幆浣割浖閿燂拷
    private static void showMsgBoxYesOrNo(final String[] array) {
        CCJNIHelper.sCCJNIHelperListener.showMsgBoxYesOrNo(array);
    }

    private static void showMsgBoxYesOrNo(final String pTitle,
                                          final String pMessage) {
        CCJNIHelper.sCCJNIHelperListener.showMsgBoxYesOrNo(pTitle, pMessage);
    }

    // 濞戞挸顑堝ù锟�
    // Cool.Cat
    public static void runDownload(final String Url) {
        CCJNIHelper.sCCJNIHelperListener.runDownload(Url);
    }

    // 閻庣懓顦抽ˉ锟�
    // Cool.Cat
    public static void runSetup(final String path) {
        Intent intent = new Intent(Intent.ACTION_VIEW);
        Uri uri = Uri.parse("file://" + path);
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setDataAndType(uri, "application/vnd.android.package-archive");
        CCJNIHelper.sContext.startActivity(intent);
        
  //聽瑕嗙洊瀹夎
  //  	if聽(intent.getAction().equals("android.intent.action.PACKAGE_REPLACED"))聽{
  //  	聽聽聽聽聽String聽packageName聽=聽intent.getDataString();
  //  	聽聽聽聽聽System.out.println("android.intent.action.PACKAGE_REPLACED---------------"聽+聽packageName);
  //  	聽}
        
    }

    // 闁兼儳鍢茶ぐ鍥偨閵婏箑鐓戦柣褍顭峰▍銏＄┍閳╁啩绱�
    public static String getUserLoginInfo() {
        return m_strUserLoginInfo;
    }

    public static void setUserInfo(final String userName, final String password, final int iEnterMode)
    {
        UserName = userName;
        Password = password;
        m_iEnterMode = iEnterMode;
    }

    public static void startGameApp(final String packageName)
    {
        Intent intent = new Intent(Intent.ACTION_MAIN);

        int last = packageName.lastIndexOf(".");
        String strActivity = packageName + packageName.substring(last);
        intent.setComponent(new ComponentName(packageName, strActivity));

        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.putExtra("UserName",UserName);
        intent.putExtra("password",Password);
        intent.putExtra("packageName", CCJNIHelper.sContext.getPackageName());
        intent.putExtra("iEnterMode", m_iEnterMode);

        CCJNIHelper.sContext.startActivity(intent);
    }

    public static void startGameHall(final String packageName)
    {
        Intent LaunchIntent = CCJNIHelper.sContext.getPackageManager().getLaunchIntentForPackage(packageName);
        LaunchIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK|Intent.FLAG_ACTIVITY_SINGLE_TOP);
        CCJNIHelper.sContext.startActivity(LaunchIntent);
    }

    public static int isApkInstalled(final String packageName, final String versionInfo)
    {
        Log.i("TAG_isApkInstalled","packageName = "+ packageName + "++++versionInfo = " + versionInfo);

        try {
            PackageManager pakage_Manager = CCJNIHelper.sContext.getPackageManager();
            Log.i("TAG_isApkInstalled","packagemanager");
            // 闁兼儳鍢茶ぐ鍢漚ckageManager閻庣數顢婇挅锟�  ,PackageManager.GET_UNINSTALLED_PACKAGES
            ApplicationInfo applicatonInfo = pakage_Manager.getApplicationInfo(packageName, PackageManager.GET_UNINSTALLED_PACKAGES);
            if (applicatonInfo == null)
            {
                return -1;
            }

            PackageInfo info = CCJNIHelper.sContext.getPackageManager().getPackageInfo(packageName, 0);
            // 鐟滅増鎸告晶鐘虫償閺冨倹鏆忛柣銊ュ婢ф寮甸锟介幃鏇犵矓閿燂拷
            String versionName = info.versionName;
            versionName = versionName.replace(".", "");
            Log.i("TAG_isApkInstalled", "鐟滅増鎸告晶鐘虫償閺冨倹鏆忛柣銊ュ婢ф寮甸锟介幃鏇犵矓閿燂拷 = " + versionName);
            // 鐟滅増鎸告晶鐘绘偋閸喐鎷遍柣銊ュ婢ф寮甸锟借ぐ锟�
            int versionCode = info.versionCode;
            Log.i("TAG_isApkInstalled", "鐟滅増鎸告晶鐘绘偋閸喐鎷遍柣銊ュ婢ф寮甸锟借ぐ锟�   = " + versionCode);
            // 鐟滅増鎸告晶鐘绘偋閸喐鎷遍柣銊ュ鐎垫﹢宕ラ敓锟�            String packageNames = info.packageName;
            Log.i("TAG_isApkInstalled", "鐟滅増鎸告晶鐘绘偋閸喐鎷遍柣銊ュ鐎垫﹢宕ラ敓锟� = " + packageName);

            if (!versionName.equals(versionInfo))
                return -1;

            return 0;
            //return UNINSTALLED+"";

        } catch (NameNotFoundException e) {
        	Log.i("TAG_isApkInstalled","Namenotfound");
            String strError = e.getMessage();
            e.printStackTrace();
            //runDownload(DownLoadURL);
            return -2;
        } catch (NullPointerException e) {

            String strError = e.getMessage();
            e.printStackTrace();
            //runDownload(DownLoadURL);
            return -2;
        }
    }

    //濠㈣泛绉撮崺妤呭礆閺夊灝顥呴悹鎰摠濠拷
    public static void setAndroidClip(final String strUrl)
    {
        Log.v("setAndroidClip", strUrl);

        m_Clipboard.setText(strUrl); // 濠㈣泛绉撮崺锟�
    }

    //闁绘稒褰冭ぐ鍥礆閺夊灝顥呴悹鎰摠濠拷
    public static String getAndroidClip()
    {
        String StrClip = m_Clipboard.getText().toString(); //缂侇喗顭堥崚锟�

        return StrClip;
    }

    private boolean isRunningForeground (Context context)
    {
        ActivityManager am = (ActivityManager)context.getSystemService(CCJNIHelper.sContext.ACTIVITY_SERVICE);
        ComponentName cn = am.getRunningTasks(1).get(0).topActivity;
        String currentPackageName = cn.getPackageName();
        if(currentPackageName.equals(getPackageName()))
        {
            return true ;
        }

        return false ;
    }
    
    
    // ===========================================================
    // 获取设设备信息
    // Add by linyuenan 06.03.31
    // ===========================================================
    // 设备型号
 	public static String getDeviceModel() {
 		return Build.MODEL;
 	}

 	// 设备序列号
 	public static String getSerial() {
 		return Build.SERIAL;
 	}
 	
 	// 获取mac
 	public static String getMacAddress() {
 		WifiManager wifi = (WifiManager) CCJNIHelper.sContext
 				.getSystemService(Context.WIFI_SERVICE);
 		if (wifi == null)
 			return null;
 		WifiInfo info = wifi.getConnectionInfo();
 		if (info == null)
 			return null;
 		return info.getMacAddress();
 	}
 	
 	// 获取IMSI
 	public static String getIMSI() {
 		TelephonyManager tm = (TelephonyManager) CCJNIHelper.sContext
 				.getSystemService(Context.TELEPHONY_SERVICE);
 		if (tm == null)
 			return null;
 		String IMSI = tm.getSubscriberId();
 		if (IMSI == null)
 			return null;
 		if (IMSI.startsWith("46000") || IMSI.startsWith("46002")) {
 			Log.v("debug", "中国移动");
 		} else if (IMSI.startsWith("46001")) {
 			Log.v("debug", "中国联通");
 		} else if (IMSI.startsWith("46003")) {
 			Log.v("debug", "中国电信");
 		}
 		return IMSI;
 	}

 	// 获取IMEI
 	public static String getIMEI() {
 		TelephonyManager tm = (TelephonyManager) CCJNIHelper.sContext
 				.getSystemService(Context.TELEPHONY_SERVICE);
 		if (tm == null)
 			return null;
 		return tm.getDeviceId();
 	}
 	
 	// 获取IMEI SV
 	public static String getIMEISV() {
 		TelephonyManager tm = (TelephonyManager) CCJNIHelper.sContext
 				.getSystemService(Context.TELEPHONY_SERVICE);
 		if (tm == null)
 			return null;
 		return tm.getDeviceSoftwareVersion();
 	}

 	// 获取电话号码
 	public static String getPhoneNumber() {
 		TelephonyManager tm = (TelephonyManager) CCJNIHelper.sContext
 				.getSystemService(Context.TELEPHONY_SERVICE);
 		if (tm == null)
 			return null;
 		return tm.getLine1Number();
 	}

    // ===========================================================
    // Inner and Anonymous Classes
    // ===========================================================
    public static interface CCJNIFuncListener {
        public void showMsgBoxYesOrNo(final String[] pArray);

        public void showMsgBoxYesOrNo(final String pTitle, final String pMessage);

        public void runDownload(final String Url);

    }
}

